#!/usr/bin/python
#-*- encoding: utf-8 -*-

import cookielib, urllib2, urllib
import re
import getpass
import time
import threading
 
class Discuz:
    def __init__(self, uid, pwd, **param):
        self.username = uid
        self.password = pwd
        self.para = param
        self.regex = {
            'loginreg':'<input\s*type="hidden"\s*name="formhash"\s*value="([\w\W]+?)"\s*\/>',
            'postreg':'<input\s*type="hidden"\s*name="formhash"\s*id="formhash"\s*value="([\w\W]+?)"\s*\/>'
        }
        self.opener = None
        self.request = None
        self.islogin = False
        self.donecount = 0
        self.__login()
        self.threadcount = 100    #总线程数
        self.count = 0
        self.totalcount = 100000   #发帖量
    
    def __login(self):
        try:
            loginPage = urllib2.urlopen(self.para['loginurl']).read()
            formhash = re.search(self.regex['loginreg'], loginPage)
            formhash = formhash.group(1)
            print formhash
            print 'start login......'
            cookiejar = cookielib.CookieJar()
            self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
            values = {
                         'formhash':formhash,
                         'username':self.username,
                         'password':self.password,
                         'loginsubmit':'true'
                     }
            data = urllib.urlencode(values)
            self.request = urllib2.Request(self.para['loginsubmiturl'], data)
            #rq = self.opener.open(self.request)
 
            #print 'login success......'
            self.islogin = True
 
        except Exception , e:
            print 'Loggin Error:%s' % e
    def Post(self, subject, wysiwyg, content):
        threads = []
        for i in range(self.threadcount):
            t = threading.Thread(target=self.__postTopic, kwargs={'_subject':subject, '_wysiwyg':wysiwyg, '_body':content})
            threads.append(t)
        for i in range(self.threadcount):
            threads[i].start()
        #lst = threading.enumerate()
        for i in range(self.threadcount):
            threads[i].join()
        print 'done'
    def __postTopic(self, **para):
        if not self.islogin:
            print 'please login......'
            return
        while self.count < self.totalcount:
            try:
                print 'current count %d:' % self.count
                print 'current thread name %s' % (threading.currentThread().getName())
                self.request = urllib2.Request(self.para['posturl'])
                rq = self.opener.open(self.request)
                data = rq.read()
                formhash = re.search(self.regex['postreg'], data)
                formhash = formhash.group(1)
                postdata = {
                    'addtags':'+可用标签',
                    'checkbox':'0',
                    'formhash':formhash,
                    'iconid':'',
                    'message':para['_body'],
                    'subject':para['_subject'],
                    'tags':'',
                    'updateswfattach' : '0',
                    'wysiwyg' : para['_wysiwyg']
                }
                self.request = urllib2.Request(self.para['postsubmiturl'], urllib.urlencode(postdata))
                self.opener.open(self.request)
                self.donecount += 1
                print '%d done.....' % self.donecount
            except Exception, e:
                print e
            if para.has_key('sleep'):
                time.sleep(float(para['sleep']))
            self.count += 1
 
if __name__ == '__main__':
    name = raw_input('username:').strip()
    password = getpass.getpass('password:').strip()
    dz = Discuz(name, password,
    loginurl='http://localhost/logging.php?action=login',
    loginsubmiturl='http://localhost/logging.php?action=login&loginsubmit=yes',
    posturl='http://localhost/post.php?action=newthread&fid=28',
    postsubmiturl='http://localhost/post.php?&action=newthread&fid=28&extra=&topicsubmit=yes',
    sleep='1'
    )
    content = '''新手如何 练级更加快？？送极品装备！新手必看
绑定升级钻石账号方法超简单：
1 新用户：直接到推广页面[url=http://tg.sdo.com/38797039]http://tg.sdo.com/38797039[/url]注册账号时在“推广员账号”一栏填推广员号adaccount直接升级钻石账号。
2 已经注册盛.大通行证的玩家在这里绑定直接成为 钻石账号 玩家
第一步: 点此 预绑定用户认证 [url=http://178.sdo.com/web/ConsumerBindUser.aspx]http://178.sdo.com/web/ConsumerBindUser.aspx[/url]
第二步: 点此进行最终绑定确认 [url=http://gift.sdo.com/Consumer/AIONBindUser.aspx]http://gift.sdo.com/Consumer/AIONBindUser.aspx[/url]
 
推广员填:adaccount'''
 
    dz.Post('送极品装备！新手必看', '1', content)
